(function($) {
	var base = this;
	
	base.poGenerator = function() {
		// Set properties
		base.parent_po_cbx = '#tbl-processing .main-po-item';
		base.child_po_cbx = '#tbl-processing .po-item';
		base.main_container = '#items-container .groups';
		base.messages = {};
		base.po_reload = false;

		// Prepare Table Header
 		var header_data_row = [ 'Item ID', 'Product ID', 'Name', 'Model', 'Size', 'Branch', 'QTY', 'SRP', 'Remove' ];
		var header_row = '<tr class="info"><th>' + header_data_row.join('</th><th>') + '</th></tr>';

		// Prepare company container template
		var comp_container = $('<div>').append('<h4 style="color: #1e91cf;"></h4>');
		var company_table = $('<table>').addClass('table table-bordered table-striped table-hover');
		base.comp_container = comp_container.append(company_table.append(header_row));
		
		// Prepare PO Table Header
		var po_data_row = [ 'Product ID', 'Name', 'Model', 'Size', 'Options', 'QTY', 'SRP', 'Additional Price', 'Total' ];
		var po_row = '<tr class="info"><th>' + po_data_row.join('</th><th>') + '</th></tr>';

		// Prepare PO container template
		var po_table = $('<table>').addClass('table table-bordered table-striped table-hover');
		base.po_container = $('<div>').append(po_table.append(po_row));

		// Run Initial Process.
		base.init();
	}

	/**
	 * Initialize Assigments.
	 */
	base.init = function() {
		// Active Vendor. 0 for All Vendors
		filters.vendor = $('select#filter_vendor').val();

		// Disable checkbox when there's no supplier
		$(base.parent_po_cbx + ', ' + base.child_po_cbx).prop('disabled', (filters.vendor == 0));

		// Has no selected items?
		if ( selected_items.length == 0 ) {
			base.toggleContainer();
		} else {
			base.loadOrderItems();
		}

		// Load Initial Events.
		base.initEvents();
	};
	
	/**
	 * Reload Purchase Order Products and PO Modal.
	 */
	base.load = function () {
		base.displayItems();

		// Check selected items in list
		$(base.child_po_cbx).each(function() {
			$(this).prop('checked', (base.isExists($(this).attr('data-id'))));
		});

		// Are all items checked? Check also parent checkbox.
		$(base.parent_po_cbx).prop('checked', ($(base.child_po_cbx).length == $(base.child_po_cbx + ':checked').length) );
	};

	/**
	 * Initial Load Events.
	 */
	base.initEvents = function() {
		// Parent Checkbox Event
		$(document).on('click', base.parent_po_cbx, function() {
			var is_parent_checked =  $(this).is(':checked');
			
			$(base.child_po_cbx).each(function() {
				if ( is_parent_checked ) 
					base.loadItem( $(this) );
				else
					base.removeItem( $(this) ); 

				$(this).prop('checked', is_parent_checked);
			});

			base.toggleContainer();
		});

		// Processing Table Checkbox Check Event
		$(document).on('click', base.child_po_cbx, function(target) {
			if ( $(this).is(':checked') ) {
				base.loadItem( $(this) );

				// Is all items checked? Check also parent checkbox.
				if ( $(base.child_po_cbx).length == $(base.child_po_cbx + ':checked').length )
					$(base.parent_po_cbx).prop('checked', true);
			} else {
				base.removeItem( $(this) );

				// Is parent checkbox selected? Uncheck it.
				if ( $(base.parent_po_cbx).is(':checked') ) 
					$(base.parent_po_cbx).prop('checked', false);
			}

			base.toggleContainer();
		});

		// Order Products Table Checkbox Check Event
		$(document).on('click', 'button.remove-po', function(target) {
			base.removeItem( $(this) );

			// Is parent checkbox selected? Uncheck it.
			if ( $(base.parent_po_cbx).is(':checked') ) 
				$(base.parent_po_cbx).prop('checked', false);

			base.toggleContainer();
		});

		// Processing Filter Event
		$(document).on('click', '#filter', function() {
			var new_vendor = $('select#filter_vendor').val();

			// Is new Vendor selected? Reset All
			if ( filters.vendor != new_vendor ) {
				base.resetAll();
				filters.vendor = new_vendor;
			}

			// Disable checkbox when there's no supplier
			$(base.parent_po_cbx).prop('disabled', (filters.vendor == 0));
		});
		
		// Preview PO Preview Button
		$('#prevPoModal').on('shown.bs.modal', function() {
			base.loadOrderItems(1);
		});
		
		// Close PO Preview Button
		$('#prevPoModal').on('hidden.bs.modal', function() {
			$(this).find('.modal-body').slideUp();
			
			if ( base.po_reload ) {
				$('#list-container').showList(window.location);
			}

			base.displayMessages();
		});
		
		// Generate PO event
		$('#generatePo').on('click', function() {
			var comments = {};
			$('#prevPoModal textarea').each(function(){
				var company_id = $(this).attr('name');
				var comment = $(this).val();
				comments[company_id] = comment;
			});

			$.ajax({
				url: $('base').attr('href') + "/processing/generatePo",
				type: 'POST',
				data: { vendor_id: filters.vendor, items: selected_items.join(), comments: comments },
				dataType: 'json',
				success: function(data) {
					var pos = data['purchase_orders'];
					messages = data['messages'];
					
					if ( pos.length ) {
						messages.info_items = [];

						// Open new tab, especially for multiple items. 
						for ( var i = 0; i < pos.length; i++ ) {
							window.open($('base').attr('href') + '/po/export/' + pos[i] + '/default/1', '_blank');
						}
						messages.info_items = pos;
						messages.info = 'Purchase Order(s) have been successfully added.';
					}
				},
				complete: function (data) {
					base.resetAll();
					$('#prevPoModal .modal-body').find('div[role="tabpanel"]').remove();
					$('#generatePo').remove();
					displayMessages();
					base.po_reload = true;
				}
			});
		});
	};

	/**
	 * Reset stored items in Window.
	 */
	base.resetAll = function( ) {
		window.selected_items = [];
		window.data_items = {};
		window.po_items = {};
		$('#items-container .groups').html('');

		// Debugger
		console.log('Items for PO has been successfully reset.');
	}

	/**
	 * Add item in Order Products list.
	 */
	base.loadItem = function( item ) {
		var id = item.val();
		var item_data = item.data();
		var company = item_data.company;

		// Item exists already?
		if ( base.isExists( id ) === false ) {
			// Is new Company group?
			if ( !$('#po-' + company).length ) {
				// Create Company Table and List
				data_items[company] = {};
				base.createCompanyDiv( company );

				// Debugger
				console.log('Added new Company ' + company);
			}

			// Add in company list data and selected items
			data_items[company][id] = item_data;
			selected_items.push(id);

			// Append row in its Company Table
			var item_data_row = [ id, item_data.prod_id, item_data.prod_name, item_data.prod_model, item_data.size_code, item_data.branch, 
				item_data.prod_qty, parseFloat(item_data.prod_srp).toFixed(2), '<button class="remove-po btn-warning" data-id="' + id + '" data-company="' + company + '">X</button>' ];
			var item_row = '<tr id="po-item-' + id + '"><td>' + item_data_row.join('</td><td>') + '</td></tr>';

			$('#po-' + company).find('table').append(item_row);

			// Debugger
			console.log('Added item #' + id + ' to Company ' + company);
		}
	};

	/**
	 * Remove item in Order Products list.
	 */
	base.removeItem = function ( item ) {
		var id = item.attr('data-id');

		// Item doesn't exist?
		if ( base.isExists( id ) === false ) return;

		var company = item.attr('data-company');
		var comp_items_count = base.compItemsCount(data_items[company]);

		// Has only one remaining row in Company? Delete Whole group.
		if ( comp_items_count === 1 ) {
			// Remove Company container and items
			$('#po-' + company).remove();
			delete data_items[company];
		} else {
			// Remove Item row in Company Table and data items
			$('#po-item-' + id).remove(); 
			delete data_items[company][id];
		}

		// Uncheck item from Processing list
		$('input[value=' + id + ']').prop('checked', false);
		
		// Remove in selected items
		var idx = base.isExists( id );
		if ( idx >= 0 )
			selected_items.splice( idx, 1 );

		// Debugger
		console.log('Removed item #' + id + ' from Company ' + company);
	};

	/**
	 * Load Selected Order Items based.
	 */
	base.loadOrderItems = function () {
		var processing_url = $('base').attr('href') + "/processing/getOrderItems/" + selected_items.join() + "/" + filters.vendor;
		
		if ( typeof (arguments[0]) != 'undefined' ) {
			processing_url = processing_url + '/1';
			$('#generatePo').prop('disabled', true);
		}

		$.ajax({
			url: processing_url, 
			type: 'GET',
			async: false,
			dataType: 'json',
			success: function (data) {
				// Set new Selected Items and Data Items
				selected_items = data['selected_items'];
				data_items = data['data_items'];
				po_items = data['po_items'];
				messages = data['messages'];

				// Debugger
				console.log('Data Loaded: '); console.log(data);
			},
			complete: function (data) {
				base.load();
				
				// has PO items?
				if ( selected_items.length ) {
					base.displayPoItems();
					base.displayMessages();
				}
				else {
					base.displayMessages();
					base.po_reload = true;
				}
			}
		});
	}
	
	/**
	 * Display messages.
	 */
	base.displayMessages = function () {
		var msgs = base.messages;
		var msg_div = $('#flash_messages_modal');
		var button_close = '<button type="button" class="close" data-dismiss="alert">&times;</button>';
		var alert_tpl = $('<div>').addClass('alert alert-danger').append('<i class="fa fa-check-circle"></i><span></span>');
		var info_tpl = $('<div>').addClass('alert alert-info').append('<i class="fa fa-check-circle"></i><span></span>');

		if ( msgs.hasOwnProperty('error') ) {
			var error_items = '';
			if ( msgs.error_items.length )
				error_items += '&nbsp;ID <strong>' + msgs.error_items.join(',') + '</strong> ';
			
			$(msg_div).append(alert_tpl.clone().append(error_items + msgs.error));
		}
		
		if ( msgs.hasOwnProperty('info') ) {
			var info_items = '';
			if ( msgs.info_items.length )
				info_items += '&nbsp;ID <strong>' + msgs.info_items.join(',') + '</strong> ';
			$(msg_div).append(info_tpl.clone().append(info_items + msgs.info));
		}
		
		// reset messages stored
		base.messages = {};
	};

	/**
	 * Check item existence in Window Selected Items list.
	 * Retrieves index.
	 */
	base.isExists = function ( id ) {
		var idx = false;

		$.each(selected_items, function(index, value) { 
			if ( (id).toString() == (value).toString() )
				idx = (index).toString();
		});

		return idx;
	}

	/**
	 * Check item existence in Window Selected Rows list.
	 * Retrieves item row.
	 */
	base.isRowExists = function ( company, id ) {
		var idx = false;

		if ( data_items.hasOwnProperty(company) ) {
			if ( data_items[company].hasOwnProperty((id).toString()) )
				return data_items[company][id];
		}

		return idx;
	}

	/** 
	 * Count items under Company.
	 */
	base.compItemsCount = function ( company ) {
		var size = 0, key;

		for (key in company)
			if (company.hasOwnProperty(key)) size++;
		
	 	return size;
	};

	/**
	 * Toggle Items Container based on Selected Items count.
	 */
	base.toggleContainer = function () {
		if ( selected_items.length == 0 ) {
			$('#items-container').hide();
		} else {
			if ( $('#items-container').is(':visible') === false )
				$('#items-container').show();
		}
	};

	/** 
	 * Create Company Div and Add in Groups.
	 */
	base.createCompanyDiv = function ( company ) {
		var comp_tpl = base.comp_container.clone();
		comp_tpl.find('h4').text(company.toUpperCase());
		comp_tpl.attr('id', 'po-' + company);
		
		// Add Company Table to Order Products Container
		$('#items-container .groups').append(comp_tpl);
	};
	
	/**
	 * Display selected items grouped per company at once.
	 */	 
	base.displayItems = function () {
		if ( selected_items.length == 0 ) return;
	
		// Empty Container
		$(base.main_container).html('');
		
		for ( company in data_items ) {
			var company_items = data_items[company];
			
			var item_rows = '';
			for ( item in company_items ) {
				var item_data = company_items[item];
				var item_data_row = [ item_data.id,  item_data.prod_id, item_data.prod_name, item_data.prod_model, item_data.size_code, item_data.branch, 
					item_data.prod_qty, parseFloat(item_data.prod_srp).toFixed(2), '<button class="remove-po btn-warning" data-id="' + item_data.id + '" data-company="' + company + '">X</button>' ];
				item_rows += '<tr id="po-item-' + item_data.id + '"><td>' + item_data_row.join('</td><td>') + '</td></tr>';
			}
			
			// Append row in its Company Table
			base.createCompanyDiv(company);
			$('#po-' + company).find('table').append(item_rows);
		} 
	};
	
	/**
	 * Display PO Items.
	 */
	base.displayPoItems = function ( ) {
		$('#prevPoModal .modal-body').hide();
		
		var vendor_name = $('#filter_vendor option[value=' + filters.vendor + ']').text();
		$('#prevPoLabel').text('Purchase Order For ' + vendor_name);

		var main_tab_panel = $('<div role="tabpanel">');
		var main_nav = $('<ul class="nav nav-tabs" role="tablist">');
		var main_content = $('<div class="tab-content">');
		var main_nav_li = $('<li role="presentation"><a href="#" role="tab" data-toggle="tab"></a></li>');
		var main_content_grp = $('<div role="tabpanel" class="tab-pane fade">');
		
		for ( company in po_items ) {
			var comp_name = 'po_' + company;
			var group_data = po_items[company];
			var group_div = main_content_grp.clone().attr('id', comp_name);
			var group_content = po_container.clone();
			
			// Add Company in Tab Nav
			var comp_li = main_nav_li.clone();
			comp_li.find('a').attr('href', '#' + comp_name).attr('aria-controls', comp_name).text(company.toUpperCase().replace('_', ' '));
			main_nav.append(comp_li);

			var item_rows = '';
			for ( item in group_data['items'] ) {
				var item_data = group_data['items'][item];
				var options_data = group_data['items'][item]['options']['items'];
				var option_total = group_data['items'][item]['options']['total'];
	
				// Build Options Description
				var option = '';
				for ( opt in options_data ) {
					var opt_data = options_data[opt];
					option = option + opt + ' (' + parseFloat(opt_data.opt_price).toFixed(2) + ') - ' + opt_data.opt_qty + ' <br/>';
				}
				
				var item_data_row = [ item_data.prod_id, item_data.prod_name, item_data.prod_model, item_data.size_code, option,
					item_data.prod_qty, parseFloat(item_data.prod_srp).toFixed(2), parseFloat(option_total).toFixed(2), parseFloat(item_data.prod_total).toFixed(2)];
				item_rows += '<tr><td>' + item_data_row.join('</td><td>') + '</td></tr>';
			}
			
			// Add rows in PO table
			var total_row = '<tr><td colspan="9" class="text-right"><strong>' + parseFloat(group_data['total']).toFixed(2) + '</strong></td></tr>'
				+ '<tr><td rowspan="2" colspan="9"><strong>Shipping Address: </strong>' + group_data['shipping_address'] + '</td></tr>';
			var comment = '<textarea style="overflow:auto;resize:none" cols="100" rows="5" name="' + comp_name + '" placeholder="Input your comments here..."></textarea>';
			group_content.find('table').append(item_rows).append(total_row);
			group_content.append(comment);
			main_content.append(group_div.html(group_content));
		}

		main_tab_panel.append(main_nav);
		main_tab_panel.append(main_content);
		$('#prevPoModal .modal-body').html(main_tab_panel).prepend($('<div>').attr('id', 'flash_messages_modal'));
		$('#prevPoModal ul.nav-tabs').find('li').eq(0).addClass('active');
		$('#prevPoModal div.tab-content').find('.tab-pane').eq(0).addClass('in active');
		$('#prevPoModal .modal-body').slideDown();
		$('#generatePo').prop('disabled', false);
	}
})(jQuery);

/**
 * Format Date Fields.
 * @author AngelaMisa 02/18/2015
 * @param elems, format, max_date
 * @return void
 */
function formatDatePickers( elems, format, max_date ) {
	for ( var i = 0; i <= elems.length; i++ ) {
		$(elems[i]).datetimepicker({
			format: format,
			maxDate: max_date
		});
	}
}

$(document).ready(function(){
	// Holds selected items, items per company
	window.selected_items = window.selected_items || [];
	window.data_items = window.data_items || {};
	window.po_items = window.po_items || {};
	window.filters = window.filters || {};

	// Add formatted for Date fields
	var date_elems = ['input[name="filter_order_date_to"]', 'input[name="filter_order_date_from"]'];
	formatDatePickers(date_elems, 'MM/DD/YYYY', '{{ $cur_date }}');

	var generator = new poGenerator();
});